import { join } from 'path';
import * as vscode from 'vscode';
import { onRelyByFile, getDataByrootPath } from '../tools/onrely';
import { DataTreeDataProvider, } from './treeDataProvider';
export class ExplorerView {

  currFileName = "";

  dataTreeDataProvider = new DataTreeDataProvider();

  constructor(context: vscode.ExtensionContext) {
    const view = vscode.window.createTreeView('relyonEView', { treeDataProvider: this.dataTreeDataProvider, showCollapseAll: true });
    context.subscriptions.push(view);
    vscode.commands.registerCommand('relyon.reveal', async () => {
      const key = await vscode.window.showInputBox({ placeHolder: 'Type the label of the item to reveal' });
      if (key) {
        await view.reveal({ key }, { focus: true, select: false, expand: true });
      }
    });
    vscode.commands.registerCommand('relyonEView.refresh', () => {
      if (this.currFileName) {
        this.setViewData();
      }
    });
    vscode.commands.registerCommand('relyon.openFile', resource => this.openResource(resource));

    vscode.commands.registerCommand('relyon.changeTitle', async () => {
      const title = await vscode.window.showInputBox({ prompt: 'Type the new title for the Test View', placeHolder: view.title });
      if (title) {
        view.title = title;
      }
    });
    vscode.window.onDidChangeActiveTextEditor((textEditor: vscode.TextEditor | undefined) => {
      if (textEditor) {
        this.currFileName = textEditor.document.fileName;
        this.setViewData();
      }
    });
    const textEditor = vscode.window.activeTextEditor;
    if (textEditor) {
      this.currFileName = textEditor.document.fileName;
      this.setViewData();
    }
  }


  private openResource(resource: vscode.Uri): void {
    vscode.window.showTextDocument(resource);
  }

  setViewData() {
    const rootPath = onRelyByFile(join(this.currFileName, '..'));
    console.log('rootPath', rootPath);
    const data = getDataByrootPath(rootPath);
    const onRelyData = data.files[this.currFileName];
    this.dataTreeDataProvider.setData(onRelyData, rootPath);
    this.dataTreeDataProvider.refresh();
  }

}